﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Grishko.DataTier.SqlSentence;
using Ecopsy.Tools;
using Grishko.UI;

public partial class Ctl_ctlFilterItemEditor : System.Web.UI.UserControl
{
    Word _SentenceWord = null;
    ScriptEngine _ListWhereSource = null;



    public ScriptEngine  ListWhereSource
    {
        get { return _ListWhereSource; }
        set { _ListWhereSource = value;}
    }

    public Word SentenceWord
    {
        get { return _SentenceWord; }
         set {
             _SentenceWord = value;             
         } 
    }

    public string  ImCallBind
    {
        get
        {   
            return "";
        }
        set 
        {
            string r = value;
            MyBind();
        }
    }
        
    /// <summary>
    /// Выбранное поле 
    /// </summary>
    /// 
    private Word _SelectedField = null;
    protected Word SelectedField 
    {

        get { 
            if(null==cmbFields.SelectedItem)
                return null;

            if(_SelectedField ==null)
                _SelectedField = ListWhereSource.GetSentenceDictionaryField(cmbFields.SelectedItem.Value);

            return _SelectedField;
            
        }
        set {;}
    }

    /// <summary>
    /// Выбранная операция
    /// </summary>
    protected Word.OperatorTypes SelectedFieldOperation
    {
        get
        {
            return Word.ConverStringToOperatorType(cmbFieldOperations.SelectedItem.Value);
            
        }
    }

    protected Word .WordTypes  SelectedSentenceWordType
    {
        get
        {
            if (cmbWordOperation.SelectedItem.Value == Word.WordTypes.AND.ToString())
                return Word.WordTypes.AND;

            return Word.WordTypes.OR; 
        }
    }
    
    
    protected void MyBind()
    {
        Func<ListItem[]> GetFieldList = delegate()
        {

            Word[] fields = ListWhereSource.GetSentenceDictionary().ToArray<Word>();
            List<ListItem> l = new List<ListItem>();
            foreach (Word i in fields)
            {
                if(string.IsNullOrEmpty ( i.PropertyName ))
                                                    continue ;
                ListItem ii = new ListItem()
                {
                    Text = i.TxtKey,
                    Value = i.PropertyName 
                };
                l.Add(ii);
            }
            return l.ToArray<ListItem>();
        };
        Func<List<ListItem>> GetWordOperationList = delegate()
        {
            List<ListItem> result = new List<ListItem>();
            ListItem ii = new ListItem() { Text = "И", Value = Word.WordTypes.AND.ToString() };
            result.Add(ii);
            ii = new ListItem() { Text = "ИЛИ", Value = Word.WordTypes.OR.ToString() };
            result.Add(ii);
            return result;
        };
        

        cmbFields.Items.AddRange(GetFieldList());
        
        cmbWordOperation.Items.AddRange(GetWordOperationList().ToArray ());

        PopulateFieldOperations();

        cmbFieldOperations_SelectedIndexChanged(null, null);
        
 
    }
    
    protected void Page_Load(object sender, EventArgs e)
    {

    }

    protected void cmbFields_SelectedIndexChanged(object sender, EventArgs e)
    {
        PopulateFieldOperations();
        SetValueControl();
    }

    

    /// <summary>
    /// Заполнить набор допустимых операций по полю
    /// </summary>
    
    private void PopulateFieldOperations()
    {
        cmbFieldOperations.Items.Clear();
        if (null == SelectedField)
                            return;


       Word.OperatorTypes[] t=  Word.GetAllowedOperatorsForPropertyType(SelectedField.PropertyType);
       foreach (WhereSentenceWord.SentenceWordOperatorTypes i in t)
       { 
           ListItem lv=new ListItem();
           lv.Text =i.ToString ();
           lv.Value  =i.ToString ();
           cmbFieldOperations.Items.Add(lv); 
       }
    
    }

    /// <summary>
    /// Установить контрол значения в зависимости от поля и опреации
    /// </summary>
    private void SetValueControl()
    {
        string s = SelectedField.PropertyName;
        Word  f = ListWhereSource.GetSentenceDictionaryField(s, SelectedFieldOperation);
        if (f.Value is WordFieldValue_Date)
        {
            MultiView1.ActiveViewIndex = 1;
            return;
        }

        if (f.Value is  WordFieldValue_DateBetween)
        {
            MultiView1.ActiveViewIndex = 2;
            return;
        }

        if (f.Value is WordFieldValue_Number)
        {
            MultiView1.ActiveViewIndex = 3;
            return;
        }

        if (f.Value is WordFieldValue_NumberBetween)
        {
            MultiView1.ActiveViewIndex = 4;
            return;
        }

        if (f.Value is WordFieldValue_Bool)
        {
            MultiView1.ActiveViewIndex = 5;
            return;
        }

        if (f.Value is WordFieldValue_TreeValue)
        {
            MultiView1.ActiveViewIndex = 6;
            tv_TreeType.F_DataSource = AppEnvironment.DictionarySource.GetTreeDictionaryItem_F(f.SrchItemInfo.TreeDictionaryTypeID);
            tv_TreeType.DataBind();

            return;
        }


        MultiView1.ActiveViewIndex = 0;
            

    }

    protected void cmbFieldOperations_SelectedIndexChanged(object sender, EventArgs e)
    {
        SetValueControl();

    }

    /// <summary>
    /// Формирует значение слова
    /// считывает значение с конролов и выставляет значения в  Sentence
    /// Вызывается снаружи
    /// </summary>
    public void FixedSentenceValue ()
    {
        string s = SelectedField.PropertyName;
        Word  f = ListWhereSource.GetSentenceDictionaryField(s, SelectedFieldOperation);

        if (null == SelectedField)
            return;
        
        Word w = (Word)ListWhereSource.Sentence.WordList[_SentenceWord.ID];

        w.WordType = SelectedSentenceWordType;
        w.Operator = SelectedFieldOperation;        
        w.TxtKey = f.TxtKey;
        w.PropertyName = f.PropertyName;
        w.PropertyType = f.PropertyType;
        w.Value = SelectedValue;
        w.SrchItemInfo = f.SrchItemInfo; 
               
    }

    /// <summary>
    ///  в зависимости от 
    /// </summary>
    /// <returns></returns>
    /// 

    public WordFieldValue  SelectedValue
    {
        get
        {
            switch (MultiView1.ActiveViewIndex)
            {
                // String
                case 0:
                    return new WordFieldValue() { Value = txtStringValue.Text };
                // String
                case 1:
                    return new WordFieldValue_Date() { StartValue = DateTimeTools.GetDate(txtDataValue.Text) };
                // String
                case 2:
                    return new WordFieldValue_DateBetween() { StartValue = DateTimeTools.GetDate(txtDataBetweenValue_Start.Text), EndValue = DateTimeTools.GetDate(txtDataBetweenValue_End.Text) };
                // String
                case 3:
                    return new WordFieldValue_Number() { Value = (String.IsNullOrEmpty(txtNumber.Text) ? 0 : Convert.ToInt32(txtNumber.Text)) };
                //
                case 4:
                    return new WordFieldValue_NumberBetween() { StartValue = Convert.ToDecimal (txtNumberStart.Text), EndValue = Convert .ToDecimal (txtNumberEnd.Text) };
                    
                case 5:
                    return new WordFieldValue_Bool() { bValue = chTrue.Checked };

                case 6:                    
                    {
                        WordFieldValue_TreeValue v = new WordFieldValue_TreeValue();
                        string s = SelectedField.PropertyName;
                        Word  f = ListWhereSource.GetSentenceDictionaryField(s, SelectedFieldOperation);
                        tv_TreeType.F_DataSource = AppEnvironment.DictionarySource.GetTreeDictionaryItem_F(f.SrchItemInfo.TreeDictionaryTypeID);
                        v.Value = tv_TreeType.TreeDictionaryItemValue;
                        return v;
                    };
            }
            return new WordFieldValue() { Value = "" };
        }
            
    }


}
